package com.example.boot3mongodb.service.impl;

import com.example.boot3mongodb.entity.Book;
import com.example.boot3mongodb.service.BookService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class BookServiceImpl implements BookService {

    private static final Logger logger = LoggerFactory.getLogger(BookServiceImpl.class);


    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public String saveObj(Book book) {
        logger.info("---MongoDB save start---");
        book.setCreateTime(addHour(new Date(),8));
        book.setUpdateTime(new Date());
        book.setExpireTime(addMinutes(1));
        mongoTemplate.save(book);
        return "save";
    }

    @Override
    public List<Book> findAll() {
        System.out.println("---mongoTemplate---findAll---");
        return mongoTemplate.findAll(Book.class);
    }

    public static Date addMinutes(int minutes) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime plusMinutes = now.plusMinutes(minutes);
        return localDateTime2Date(plusMinutes);
    }

    public static Date localDateTime2Date(LocalDateTime time) {
        ZoneId systemDefault = ZoneId.systemDefault();
        ZonedDateTime atZone = time.atZone(systemDefault);
        return Date.from(atZone.toInstant());
    }

    public static Date addHour(Date date, int hour){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        long millis = calendar.getTimeInMillis() + ((long) hour) * 3600 * 1000;
        calendar.setTimeInMillis(millis);
        return calendar.getTime();
    }
}
